#include <assert.h>
#include <time.h>
#include "SDLGame.h"
#include "Game.h"

const int TAILLE_SPRITE = 32;
const int SPRITE_WINDOW_X = 31;
const int SPRITE_WINDOW_Y = 21;

SDL_Surface *SDL_load_image(const char* filename);

void SDL_apply_surface( SDL_Surface* source, SDL_Surface* destination, int x, int y );

void FillRect(SDL_Surface * surface_screen,int x, int y, int w, int h, int color,int alpha);

void FillRectBorder(SDL_Surface * surface_screen,int x, int y, int w, int h, int color,int alpha, int border, int color_b);

void BlitSurf(SDL_Surface * surface_screen,int x, int y, int x_im, int y_im, int w_im, int h_im, char * name);

void TextSurf(SDL_Surface * surface_screen,int x,int y, char * text_e,int size,char * font_e, int r,int g, int b);

void showSpellEffect(SDL_Surface * surface_screen,int posh_x,int posh_y, int radius, int decallage_x,int decallage_y,char * img);

void SDLGameInit(SDLGame * pSdlGame)
{
	int dimx, dimy, flags, initted;
	flags = IMG_INIT_JPG | IMG_INIT_PNG;
        initted = IMG_Init(flags);
	assert(!((initted & flags) != flags));
	assert(SDL_Init(SDL_INIT_EVERYTHING)!= -1);
	/*assert(Mix_OpenAudio( 22050, MIX_DEFAULT_FORMAT, 2, 4096 ) != -1);*/
	/* Init TTF and loading font */

	assert(TTF_Init() != -1);
	dimx = SPRITE_WINDOW_X * TAILLE_SPRITE;
	dimy = SPRITE_WINDOW_Y * TAILLE_SPRITE;
	pSdlGame->surface_screen = SDL_SetVideoMode(dimx,dimy,32,SDL_SWSURFACE);

	pSdlGame->surface_grass = SDL_load_image("data/grass.bmp");
	if(pSdlGame->surface_grass==NULL)
	   pSdlGame->surface_grass = SDL_load_image("../data/grass.bmp");
	assert(pSdlGame->surface_grass!=NULL);

	pSdlGame->surface_wall = SDL_load_image("data/wall.bmp");
	if(pSdlGame->surface_wall==NULL)
	   pSdlGame->surface_wall = SDL_load_image("../data/wall.bmp");
	assert(pSdlGame->surface_wall!=NULL);

	pSdlGame->surface_chemin = SDL_load_image("data/chemin.bmp");
	if(pSdlGame->surface_chemin==NULL)
	   pSdlGame->surface_chemin = SDL_load_image("../data/chemin.bmp");
	assert(pSdlGame->surface_chemin!=NULL);

	pSdlGame->surface_background = SDL_load_image("data/background.bmp");
	if(pSdlGame->surface_background==NULL)
	   pSdlGame->surface_background = SDL_load_image("../data/background.bmp");
	assert(pSdlGame->surface_background!=NULL);

	/*pSdlGame->music = Mix_LoadMUS("data/music.wav");*/
	assert(pSdlGame->surface_screen!=NULL);
	SDL_WM_SetCaption("SKILL ROAD", NULL );

}



void SDLGameShow(SDLGame * pSdlGame)
{

	int x,y;
	int posh_x,posh_y,mnum,posm_x,posm_y;
	char str[100];
	int formula;
	int bspell;
	const Terrain *pTer = &(pSdlGame->jeu.ter);
	const Hero * pHero = &(pSdlGame->jeu.her);
 	const Jeu * pJeu = &(pSdlGame->jeu);
	int minboucle_x,maxboucle_x,minboucle_y,maxboucle_y;
	int decallage_x;
	int decallage_y;

	int hero_pos[4] = {192,0,64,128};
	char keys[4] = { 'R','T','Y','U' };


	/* On rempli L'ecran noir */
	SDL_FillRect(pSdlGame->surface_screen, &pSdlGame->surface_screen->clip_rect,
			SDL_MapRGB(pSdlGame->surface_screen->format, 0x00, 0x00, 0x00));

	if(pSdlGame->show_menu != 0){ /* Affiche le menu ou non */

	SDL_apply_surface(pSdlGame->surface_background,pSdlGame->surface_screen,0,0);

	/* Affichage du menu avec des boutons */
	BlitSurf(pSdlGame->surface_screen,SPRITE_WINDOW_X*TAILLE_SPRITE/2-275,
			1*TAILLE_SPRITE+10,0,0,551,133,"data/logo.png");

	FillRectBorder(pSdlGame->surface_screen,SPRITE_WINDOW_X*TAILLE_SPRITE/2-100, 				
			SPRITE_WINDOW_Y*TAILLE_SPRITE/2, 200, 40, 0xc6bf95,255, 2, 0xFFFFFF);

	FillRectBorder(pSdlGame->surface_screen,SPRITE_WINDOW_X*TAILLE_SPRITE/2-100, 				
			SPRITE_WINDOW_Y*TAILLE_SPRITE/2 + 50, 200, 40, 0xc6bf95,255, 2, 0xFFFFFF);
	FillRectBorder(pSdlGame->surface_screen,SPRITE_WINDOW_X*TAILLE_SPRITE/2-100, 				
			SPRITE_WINDOW_Y*TAILLE_SPRITE/2 + 100, 200, 40, 0xc6bf95,255, 2, 0xFFFFFF);
	if(pSdlGame->menukey == 0){
	FillRectBorder(pSdlGame->surface_screen,SPRITE_WINDOW_X*TAILLE_SPRITE/2-100, 				
			SPRITE_WINDOW_Y*TAILLE_SPRITE/2, 200, 40, 0xFFFFFF,128, 2, 0x000000);
	}else if(pSdlGame->menukey == 1){
	FillRectBorder(pSdlGame->surface_screen,SPRITE_WINDOW_X*TAILLE_SPRITE/2-100, 				
			SPRITE_WINDOW_Y*TAILLE_SPRITE/2 + 50, 200, 40, 0xFFFFFF,128, 2, 0x000000);

	}else{
	FillRectBorder(pSdlGame->surface_screen,SPRITE_WINDOW_X*TAILLE_SPRITE/2-100, 				
			SPRITE_WINDOW_Y*TAILLE_SPRITE/2 + 100, 200, 40, 0xFFFFFF,128, 2, 0x000000);
	}

	/* Affichage du texte qui est sur les bouttons */
	TextSurf(pSdlGame->surface_screen,SPRITE_WINDOW_X*TAILLE_SPRITE/2-55, SPRITE_WINDOW_Y*TAILLE_SPRITE/2+13,"Continue Game",17,"data/font.ttf",0,0,0);

	TextSurf(pSdlGame->surface_screen,SPRITE_WINDOW_X*TAILLE_SPRITE/2-40, SPRITE_WINDOW_Y*TAILLE_SPRITE/2+63,"New Game",17,"data/font.ttf",0,0,0);

	TextSurf(pSdlGame->surface_screen,SPRITE_WINDOW_X*TAILLE_SPRITE/2-15, SPRITE_WINDOW_Y*TAILLE_SPRITE/2+113,"Exit",17,"data/font.ttf",0,0,0);

	TextSurf(pSdlGame->surface_screen,(SPRITE_WINDOW_X-11)*TAILLE_SPRITE, (SPRITE_WINDOW_Y-1)*TAILLE_SPRITE,"Created by Maxim Gehin and Ostapenco Vladimir",17,"data/font.ttf",255,255,255);


	}else{

	/* On recupere la position du hero */

	herGetPos(pHero,&posh_x,&posh_y);

	/* On travaille avec decallage pour faire bouger l'ecran  support d'un terrain plus petit que la fenetre*/


	if(getDimx(pTer) < SPRITE_WINDOW_X){
  		decallage_x = -(SPRITE_WINDOW_X/2 - getDimx(pTer)/2) - 1;
		minboucle_x = 1;
		maxboucle_x = getDimx(pTer)-1;
	}else{
		if(posh_x <= (SPRITE_WINDOW_X/2) + 1){
  			decallage_x = 0;
		}else if(getDimx(pTer) - posh_x <= (SPRITE_WINDOW_X/2) + 1){
			decallage_x = getDimx(pTer) - (SPRITE_WINDOW_X + 2);
		}else{
			decallage_x = posh_x - ((SPRITE_WINDOW_X/2) + 1);
		}
			minboucle_x = 1+decallage_x;
			maxboucle_x = SPRITE_WINDOW_X+1+decallage_x;
	}
	if(getDimy(pTer) < SPRITE_WINDOW_Y){
			decallage_y = -(SPRITE_WINDOW_Y/2 - getDimy(pTer)/2) - 1;
			minboucle_y = 0;
			maxboucle_y = getDimy(pTer);
	}else{
		
		if(posh_y <= (SPRITE_WINDOW_Y/2) + 1){
			decallage_y = 0;
		}else if(getDimy(pTer) - posh_y <= (SPRITE_WINDOW_Y/2) + 1){
			decallage_y = getDimy(pTer) - (SPRITE_WINDOW_Y + 2);
		}else{
			decallage_y = posh_y - ((SPRITE_WINDOW_Y/2) + 1);
		}
			minboucle_y = 1+decallage_y;
			maxboucle_y = SPRITE_WINDOW_Y+1+decallage_y;
	}



	/* AFFICHER DES MURS, DES TELEPORTS ET LA TERRE */

	for (x=minboucle_x;x<maxboucle_x;++x){
		for (y=minboucle_y;y<maxboucle_y;++y){
		if (terGetXY(pTer,x,y)=='#'){ /* ON AFFICHE LE MUR */
			SDL_apply_surface(pSdlGame->surface_wall,pSdlGame->surface_screen,
					(x-decallage_x-1)*TAILLE_SPRITE,(y-decallage_y-1)*TAILLE_SPRITE);
		}else if(terGetXY(pTer,x,y)=='c'){
			SDL_apply_surface(pSdlGame->surface_chemin,pSdlGame->surface_screen,
					(x-decallage_x-1)*TAILLE_SPRITE,(y-decallage_y-1)*TAILLE_SPRITE);
		}else{ /* ON AFFICHE LA TERRE */
			SDL_apply_surface(pSdlGame->surface_grass,pSdlGame->surface_screen,
					(x-decallage_x-1)*TAILLE_SPRITE,(y-decallage_y-1)*TAILLE_SPRITE);

	                }

		if(isTeleport(pJeu->tabTeleport,pJeu->nb_teleport,x,y,herGetTerID(pHero))){
			BlitSurf(pSdlGame->surface_screen,(x-decallage_x-1)*TAILLE_SPRITE, 
				(y-decallage_y-1)*TAILLE_SPRITE,0,0,32,32,"data/portal.png");
		}
		}
		}

	

	/* AFFICHER LE PERO */


	if(herGetCooldown(pHero) <= 0){ /* Pour afficher l'attack du perso */
		BlitSurf(pSdlGame->surface_screen,(posh_x-decallage_x-1)*TAILLE_SPRITE, (posh_y-decallage_y-1)*TAILLE_SPRITE,
					hero_pos[pHero->direction],0,32,32,"data/sprite.png");
	}else{
		BlitSurf(pSdlGame->surface_screen,(posh_x-decallage_x-1)*TAILLE_SPRITE, (posh_y-decallage_y-1)*TAILLE_SPRITE,
					hero_pos[pHero->direction]+32,0,32,32,"data/sprite.png");
	}


	/* Aficchage des monstres et du DMG */

	for (mnum=0; mnum<pJeu->nb_monstre; mnum++){

		/* On recupere la position du monstre */

		monsterGetPos(&(pJeu->tabmonst[mnum]),&posm_x,&posm_y);
		
		if(monsterGetMode(&(pJeu->tabmonst[mnum])) != 1){ /* Si le monstre est en vie on l'affiche */

		sprintf(str,"data/monster%d.png",monsterGetId(&(pJeu->tabmonst[mnum])));

		BlitSurf(pSdlGame->surface_screen,(posm_x-decallage_x-1)*TAILLE_SPRITE,
				(posm_y-decallage_y-1)*TAILLE_SPRITE,0,0,32,32,str);


		if(monsterGetLastDamage(&(pJeu->tabmonst[mnum]))!=-1){ /* On affiche le dmg si monstre a eu un dmg*/
			if(monsterGetLastDamage(&(pJeu->tabmonst[mnum])) == 0){
				sprintf(str,"Miss");
			}else{
				sprintf(str,"- %d",monsterGetLastDamage(&(pJeu->tabmonst[mnum])));
			}
			TextSurf(pSdlGame->surface_screen,(posm_x-decallage_x-1)*TAILLE_SPRITE+2, (posm_y-decallage_y-1)*TAILLE_SPRITE-20+pSdlGame->frame_dmg,str,15,"data/font.ttf",255,0,0);
			if(pSdlGame->frame_dmg == 0){ /* Si le frame est egale a 0 alors l'affichage du dernier dmg est a la fin */
				monstetSetLastDamage(&(pJeu->tabmonst[mnum]),-1); /* on met last dmg a -1 */
				pSdlGame->frame_dmg = 15; /* On pose a 15 le compteur des frames */
			}else{
				pSdlGame->frame_dmg--; /* On decremente le compteur des frames */
			}
		}

		}
	}





	/* Affichage des stats du hero */

	FillRectBorder(pSdlGame->surface_screen,1*TAILLE_SPRITE, 1*TAILLE_SPRITE,
			6*TAILLE_SPRITE, 120, 0x9FC6A2,128, 2, 0x000000);

	BlitSurf(pSdlGame->surface_screen,1*TAILLE_SPRITE+10,
			1*TAILLE_SPRITE+10,32*4,0,32,32,"data/sprite.png");


	sprintf(str,"Name: %s",herGetname(pHero));
	TextSurf(pSdlGame->surface_screen,1*TAILLE_SPRITE + 54,
			1*TAILLE_SPRITE+10,str,17,"data/font.ttf",0,0,0);


	sprintf(str,"Level: %d",herGetlevel(pHero));
	TextSurf(pSdlGame->surface_screen,1*TAILLE_SPRITE + 54,
			1*TAILLE_SPRITE+27,str,15,"data/font.ttf",0,0,0);


	sprintf(str,"HP: %d / %d",herGetcurhp(pHero),herGethpmax(pHero));
	TextSurf(pSdlGame->surface_screen,1*TAILLE_SPRITE + 10,
			1*TAILLE_SPRITE+50,str,12,"data/font.ttf",0,0,0);

	formula = (herGetcurhp(pHero) * 100 / herGethpmax(pHero))*1.7;
	FillRectBorder(pSdlGame->surface_screen,TAILLE_SPRITE + 10,
			1*TAILLE_SPRITE+64, formula, 10, 0xFF0000,255, 1, 0x000000);

	sprintf(str,"MANA: %d / %d",herGetcurmp(pHero),herGetmpmax(pHero));
	TextSurf(pSdlGame->surface_screen,1*TAILLE_SPRITE + 10,
			1*TAILLE_SPRITE+84,str,12,"data/font.ttf",0,0,0);

	formula = (herGetcurmp(pHero) * 100 / herGetmpmax(pHero))*1.7;
	FillRectBorder(pSdlGame->surface_screen,TAILLE_SPRITE + 10,
			1*TAILLE_SPRITE+98, formula, 10, 0x0000FF,255, 1, 0x000000);

	if(herGetxpmax(pHero) == 0) formula = SPRITE_WINDOW_X * TAILLE_SPRITE;
	else formula = (herGetcurxp(pHero) * 100 / herGetxpmax(pHero))*((SPRITE_WINDOW_X * TAILLE_SPRITE)/100);
	FillRectBorder(pSdlGame->surface_screen,0, 0, formula, 5, 0xc0362c,255, 1, 0x000000);

	/* Mini map */

	if(pSdlGame->showmap == 1){

		FillRectBorder(pSdlGame->surface_screen,
				SPRITE_WINDOW_X * TAILLE_SPRITE - (SPRITE_WINDOW_X*9),
				SPRITE_WINDOW_Y * TAILLE_SPRITE - (SPRITE_WINDOW_X*9),
				getDimx(pTer)*2, getDimy(pTer)*2, 0x9FC6A2,128, 2, 0x000000);

	for (x=1;x<getDimx(pTer)-1;++x){
		for (y=1;y<getDimy(pTer)-1;++y){
			if (terGetXY(pTer,x,y)=='#'){

		FillRect(pSdlGame->surface_screen,
				SPRITE_WINDOW_X * TAILLE_SPRITE - (SPRITE_WINDOW_X*9) + (x*2),
				SPRITE_WINDOW_Y * TAILLE_SPRITE - (SPRITE_WINDOW_X*9) + (y*2),2,2,
				0x000000,200);

			}
			if(terGetXY(pTer,x,y)=='c'){
		FillRect(pSdlGame->surface_screen,
				SPRITE_WINDOW_X * TAILLE_SPRITE - (SPRITE_WINDOW_X*9) + (x*2),
				SPRITE_WINDOW_Y * TAILLE_SPRITE - (SPRITE_WINDOW_X*9) + (y*2),2,2,
				0x000000,64);

			}
		}
		}

		FillRect(pSdlGame->surface_screen,
				SPRITE_WINDOW_X * TAILLE_SPRITE - (SPRITE_WINDOW_X*9) + (posh_x*2),
				SPRITE_WINDOW_Y * TAILLE_SPRITE - (SPRITE_WINDOW_X*9) + (posh_y*2),3,3,
				0xDB422E,255);

	}

	/* Affichage des spells */
	for (bspell=0; bspell<herGetNbSpells(pHero); bspell++){

	/* Si notre spell et de id 2 on affiche l'effet du spell numero 2 */
	if(spellGetId(herGetSpell(pHero,bspell+1)) == 2 && spellGetCurcooldown(herGetSpell(pHero,bspell+1)) >= spellGetCooldown(herGetSpell(pHero,bspell+1)) - 0.3f){

		showSpellEffect(pSdlGame->surface_screen,posh_x,posh_y, spellGetRadius(herGetSpell(pHero,bspell+1)),decallage_x,decallage_y,"data/flame.png");

	}
	/* Si notre spell et de id 4 on affiche l'effet du spell numero 4 */
	if(spellGetId(herGetSpell(pHero,bspell+1)) == 4 && spellGetCurcooldown(herGetSpell(pHero,bspell+1)) >= spellGetCooldown(herGetSpell(pHero,bspell+1)) - 0.3f){

		showSpellEffect(pSdlGame->surface_screen,posh_x,posh_y, spellGetRadius(herGetSpell(pHero,bspell+1)),decallage_x,decallage_y,"data/rock.png");

	}
	/* On affiche le spell */
		sprintf(str,"data/Image_Spell/Spell%d.jpg",spellGetId(herGetSpell(pHero,bspell+1)));
		BlitSurf(pSdlGame->surface_screen,1*TAILLE_SPRITE, 5*TAILLE_SPRITE+60*bspell,0,0,56,56,str);

	/* L'effet de l'affichage du cooldown */ 
	formula = (int) (spellGetCurcooldown(herGetSpell(pHero,bspell+1)) * 100 / spellGetCooldown(herGetSpell(pHero,bspell+1)))* 0.56;
		
	if(formula < 0) formula = 0;

	FillRect(pSdlGame->surface_screen,1*TAILLE_SPRITE,5*TAILLE_SPRITE+60*bspell,56,formula,
				0xFFFFFF,128);

	/* Si on a pas suffisament du mana afficher le carre rouge */
	if(spellGetManacost(herGetSpell(pHero,bspell+1)) > herGetcurmp(pHero)){
		FillRect(pSdlGame->surface_screen,1*TAILLE_SPRITE,5*TAILLE_SPRITE+60*bspell,56,56,
				0xFF0000,128);
	}
	
	/* Affichages des touches */
	sprintf(str,"%c",keys[bspell]);
	TextSurf(pSdlGame->surface_screen,1*TAILLE_SPRITE+3,5*TAILLE_SPRITE+60*bspell+3,str,18,"data/font.ttf",255,255,255);
	}


	/* Affichage du attack automatique (Une epee) */
	if(herGetAttack(pHero) == 1 && herGetMode(pHero) == 2){
	formula = (int) (herGetCooldown(pHero) * 100 / herGetSpeed(pHero))* 1.28;
	if(formula < 0) formula = 0;
	BlitSurf(pSdlGame->surface_screen,1*TAILLE_SPRITE+210, 1*TAILLE_SPRITE,0,0,39,128-formula,"data/sword.png");
	}


	/* Information a propos du monstre */

	if(herGetTarget(pHero) != NULL){

	FillRectBorder(pSdlGame->surface_screen,SPRITE_WINDOW_X * TAILLE_SPRITE - (SPRITE_WINDOW_X*9), 1*TAILLE_SPRITE, 6*TAILLE_SPRITE, 120, 0x9FB7D6,128, 3, 0x000000);
	sprintf(str,"data/monster%d.png",monsterGetId(herGetTarget(pHero)));
	BlitSurf(pSdlGame->surface_screen,SPRITE_WINDOW_X * TAILLE_SPRITE - (SPRITE_WINDOW_X*9) + 20, 1*TAILLE_SPRITE+20,0,0,32,32,str);

	sprintf(str,"Name: %s",monsterGetName(herGetTarget(pHero)));
	TextSurf(pSdlGame->surface_screen,SPRITE_WINDOW_X * TAILLE_SPRITE - (SPRITE_WINDOW_X*9) + 64,1*TAILLE_SPRITE+28,str,15,"data/font.ttf",0,0,0);

	sprintf(str,"HP: %d / %d",monsterGetCurHP(herGetTarget(pHero)),monsterGetMaxHP(herGetTarget(pHero)));
	TextSurf(pSdlGame->surface_screen,SPRITE_WINDOW_X * TAILLE_SPRITE - (SPRITE_WINDOW_X*9) + 20,1*TAILLE_SPRITE+60,str,15,"data/font.ttf",0,0,0);
	formula = (monsterGetCurHP(herGetTarget(pHero)) * 100 / monsterGetMaxHP(herGetTarget(pHero)))*1.5;
	FillRectBorder(pSdlGame->surface_screen,SPRITE_WINDOW_X * TAILLE_SPRITE - (SPRITE_WINDOW_X*9) + 20, 1*TAILLE_SPRITE+84, formula, 20, 0xFF0000,255, 1, 0x000000);



	}



	}

}


void SDLGameBoucle(SDLGame * pSdlGame)
{
	SDL_Event event;
	int continue_boucle = 1;

    /* Horloges (en secondes) */
    float horloge_courante, horloge_precedente;

    /* Intervalle de temps (en secondes) entre deux évolutions du jeu */
    float intervalle_horloge = 0.01f;

    int rafraichissement;

	SDL_EnableKeyRepeat(30,100);

	pSdlGame->frame_dmg = 15;
	pSdlGame->showmap = 0;
	pSdlGame->menukey = 0;
	pSdlGame->menukey_max = 2;
	pSdlGame->show_menu = 1;
	pSdlGame->gamego = 0;

	SDLGameShow(pSdlGame);

	assert(SDL_Flip(pSdlGame->surface_screen)!=-1);

    /* Récupère l'horloge actuelle et la convertit en secondes */
    /* clock() retourne le nombre de tops horloge depuis le lancement du programme */
    horloge_precedente = (float)clock()/(float)CLOCKS_PER_SEC;

	/* assert(Mix_PlayMusic(pSdlGame->music, -1) != -1); */

	/* Tant que ce n'est pas la fin ... */
	while ( continue_boucle == 1 )
	{
	    rafraichissement = 0;

	     /* Récupère l'horloge actuelle et la convertit en secondes */
        horloge_courante = (float)clock()/(float)CLOCKS_PER_SEC;

        /* Si suffisamment de temps s'est écoulé depuis la dernière prise d'horloge */
        if (horloge_courante-horloge_precedente>=intervalle_horloge)
        {
		if(pSdlGame->show_menu == 0){
                jeuEvolue(&(pSdlGame->jeu),horloge_courante-horloge_precedente);
		}
                rafraichissement = 1;
                horloge_precedente = horloge_courante;
        }

		/* tant qu'il y a des evenements à traiter : cette boucle n'est pas bloquante */
		while ( SDL_PollEvent( &event ) )
		{


			/* Si l'utilisateur a cliqué sur la croix de fermeture */
			if ( event.type == SDL_QUIT )
				continue_boucle = 0;

			/* Si l'utilisateur a appuyé sur une touche */
			if ( event.type == SDL_KEYDOWN )
			{

                assert(event.type != SDL_KEYUP);

				switch ( event.key.keysym.sym )
				{
				case SDLK_UP:
					if(pSdlGame->show_menu != 0){
					if(pSdlGame->menukey >= 1)
					pSdlGame->menukey--;
					else pSdlGame->menukey = pSdlGame->menukey_max;
					}else{
					jeuActionClavier( &(pSdlGame->jeu), 'z');
					}
					rafraichissement = 1;
					break;
				case SDLK_DOWN:
					if(pSdlGame->show_menu != 0){
					if(pSdlGame->menukey < pSdlGame->menukey_max)
					pSdlGame->menukey++;
					else pSdlGame->menukey = 0;
					}else{
					jeuActionClavier( &(pSdlGame->jeu), 's');
					}
					rafraichissement = 1;
					break;
				case SDLK_LEFT:
					jeuActionClavier( &(pSdlGame->jeu), 'q');
					rafraichissement = 1;
					break;
				case SDLK_RIGHT:
					jeuActionClavier( &(pSdlGame->jeu), 'd');
					rafraichissement = 1;
					break;
				case SDLK_a:
					jeuActionClavier( &(pSdlGame->jeu), 'a');
					rafraichissement = 1;
					break;
				case SDLK_m:
					rafraichissement = 1;
					if(pSdlGame->showmap == 1){
						pSdlGame->showmap = 0;
					}else{
						pSdlGame->showmap = 1;
					}
					break;
                		case SDLK_r:
                    			jeuActionClavier( &(pSdlGame->jeu), 'r');
					rafraichissement = 1;
					break;
               			case SDLK_t:
                    			jeuActionClavier( &(pSdlGame->jeu), 't');
					rafraichissement = 1;
					break;
                		case SDLK_y:
                    			jeuActionClavier( &(pSdlGame->jeu), 'y');
					rafraichissement = 1;
					break;
                		case SDLK_u:
                    			jeuActionClavier( &(pSdlGame->jeu), 'u');
					rafraichissement = 1;
					break;
					case SDLK_e:
                    			jeuActionClavier( &(pSdlGame->jeu), 'e');
					rafraichissement = 1;
					break;
				case SDLK_RETURN:
					if(pSdlGame->show_menu != 0){
					if(pSdlGame->menukey == 0 && pSdlGame->show_menu == 2){
						pSdlGame->show_menu = 0;
					}else if(pSdlGame->menukey == 0){
						jeuInit(&(pSdlGame->jeu),'c');
						pSdlGame->show_menu = 0;
						pSdlGame->gamego = 1;
					}else if (pSdlGame->menukey == 1){
						jeuInit(&(pSdlGame->jeu),'n');
						pSdlGame->show_menu = 0;
						pSdlGame->gamego = 1;
					}else continue_boucle = 0;

					}
					rafraichissement = 1;
					break;
				case SDLK_ESCAPE:
					if(pSdlGame->gamego != 0){
					if(pSdlGame->show_menu != 0)
					pSdlGame->show_menu = 0;
					else
					pSdlGame->show_menu = 2;
					}
					rafraichissement = 1;
					break;
				default: break;
				}
            }
		}

        if (rafraichissement==1)
        {
            /* on affiche le jeu sur le buffer caché */
            SDLGameShow(pSdlGame);

            /* on permute les deux buffers (cette fonction ne doit se faire qu'une seule fois dans a boucle) */
            SDL_Flip(pSdlGame->surface_screen);
        }
	}
}



void SDLGameFree(SDLGame * pSdlGame)
{
	SDL_FreeSurface(pSdlGame->surface_screen);
	SDL_FreeSurface(pSdlGame->surface_grass);
	SDL_FreeSurface(pSdlGame->surface_wall);
	SDL_FreeSurface(pSdlGame->surface_chemin);
	SDL_FreeSurface(pSdlGame->surface_background);

	if(pSdlGame->gamego != 0)
	jeuFree(&(pSdlGame->jeu));
	/*Mix_FreeMusic(pSdlGame->music);*/

	TTF_Quit();
	SDL_Quit();
	/*Mix_CloseAudio();*/
}






SDL_Surface *SDL_load_image(const char* filename )
{
	/* Temporary storage for the image that's loaded */
	SDL_Surface* loadedImage = NULL;

	/* The optimized image that will be used */
	SDL_Surface* optimizedImage = NULL;

	/* Load the image */
	loadedImage = SDL_LoadBMP( filename );

	/* If nothing went wrong in loading the image */
	if ( loadedImage != NULL )
	{
		/* Create an optimized image */
		optimizedImage = SDL_DisplayFormat( loadedImage );

		/* Free the old image */
		SDL_FreeSurface( loadedImage );
	}

	/* Return the optimized image */
	return optimizedImage;
}



void SDL_apply_surface( SDL_Surface* source, SDL_Surface* destination, int x, int y )
{
	/* Make a temporary rectangle to hold the offsets */
	SDL_Rect offset;

	/* Give the offsets to the rectangle */
	offset.x = x;
	offset.y = y;

	/* Blit the surface */
	SDL_BlitSurface( source, NULL, destination, &offset );
}

void FillRect(SDL_Surface * surface_screen,int x, int y, int w, int h, int color,int alpha) {

	SDL_Surface * sfc;
	SDL_Rect rect;
	rect.x = x; rect.y = y; rect.w = w; rect.h = h;
	sfc = SDL_CreateRGBSurface(SDL_HWSURFACE, w, h, 32, 0, 0, 0, 0);
	SDL_FillRect(sfc, NULL, color);
	SDL_SetAlpha(sfc, SDL_SRCALPHA, alpha);

	SDL_BlitSurface(sfc, NULL, surface_screen, &rect);

	SDL_FreeSurface(sfc);

}




void FillRectBorder(SDL_Surface * surface_screen,int x, int y, int w, int h, int color,int alpha, int border, int color_b) {

	FillRect(surface_screen,x,y,w,h,color,alpha);

	FillRect(surface_screen,x,y,w,border,color_b,alpha);

	FillRect(surface_screen,x,y,border,h,color_b,alpha);

	FillRect(surface_screen,x+w-border,y,border,h,color_b,alpha);

	FillRect(surface_screen,x,y+h,w,border,color_b,alpha);

}

void BlitSurf(SDL_Surface * surface_screen,int x, int y, int x_im, int y_im, int w_im, int h_im, char * name){
	char str[50];
	SDL_Rect dest_rect;
	SDL_Rect conf_rect;
	SDL_Surface * img = NULL;
	img = IMG_Load(name);
	sprintf(str,"../%s",name);
	if(img == NULL)
	  img = IMG_Load(str);
	if(img == NULL)
		FillRect(surface_screen,x, y, w_im, h_im, 0xFFFFFF,255);
	dest_rect.x = x; dest_rect.y = y; dest_rect.w = 0; dest_rect.h = 0;
	conf_rect.x = x_im; conf_rect.y = y_im; conf_rect.w = w_im; conf_rect.h = h_im;

	SDL_BlitSurface(img,&conf_rect,surface_screen,&dest_rect);

	SDL_FreeSurface(img);

}

void TextSurf(SDL_Surface * surface_screen,int x,int y, char * text_e,int size,char * font_e, int r,int g, int b){
		char str[50];
		TTF_Font * font;
		SDL_Surface * text;
		SDL_Color text_color;
		text_color.r = r; text_color.g = g; text_color.b = b;

		font = TTF_OpenFont(font_e, size);
		if (font == NULL){
		sprintf(str,"../%s",font_e);
		font = TTF_OpenFont(str, size);
		}
		assert(font != NULL);

		text = TTF_RenderText_Solid( font ,text_e, text_color);
		SDL_apply_surface(text, surface_screen, x,  y );
		TTF_CloseFont( font );
		SDL_FreeSurface(text);

}


void showSpellEffect(SDL_Surface * surface_screen,int posh_x,int posh_y, int radius, int decallage_x,int decallage_y,char * img){

	int spellaff1,spellaff2, spellaff1comp, spellaff2comp;

		/*  Deux boucles qui parcourent le rectangle avec le hero a l'interieur  */
		for(spellaff1=posh_x-radius; spellaff1<=posh_x+radius;spellaff1++){
		for(spellaff2=posh_y-radius; spellaff2<=posh_y+radius;spellaff2++){
			/* On recupere la difference entre les points */
			if(spellaff1 < posh_x) spellaff1comp = posh_x - spellaff1;
						else  spellaff1comp = spellaff1 - posh_x;
			if(spellaff2 < posh_y) spellaff2comp = posh_y - spellaff2;
						else  spellaff2comp = spellaff2 - posh_y;
			/* On regarde debordement */
			if(spellaff1 > 0 && spellaff2 > 0 && spellaff1 <= TAILLE_SPRITE*SPRITE_WINDOW_X && 					spellaff2 <= TAILLE_SPRITE*SPRITE_WINDOW_Y){
			/* On affiche pas le spell sur perso */
			if(spellaff1!=posh_x || spellaff2!=posh_y){
			/* On regarde le radius d'affichage */
			if(spellaff1comp+spellaff2comp <= radius){
			/* On affiche le spell */
			BlitSurf(surface_screen,(spellaff1-decallage_x - 1)*TAILLE_SPRITE, 					(spellaff2-decallage_y - 1)*TAILLE_SPRITE,0,0,32,32,img);


			}
			}
			}
	}
	}

}

